﻿/*
 * 文件名称：
 * 程序员：wangyun
 * 创建时间：2008/05/27
 * 
 * 功能说明：自定义功能模块图标操作
 * 
 * 修改人员：huangsb
 * 
 * 修改日期：2008/06/02
 * 
 * 修改记录：
 */


using System;
using System.IO;
using System.Data;
using System.Text;

public enum FsoMethod
{
    /// <summary>
    /// 文件夹
    /// </summary>
    Folder, 

    /// <summary>
    /// 文件
    /// </summary>
    File, 

    /// <summary>
    /// 所有文件
    /// </summary>
    All
}

public class FileSystemObject
{
    /// <summary>
    /// 获得指定位置的文件信息
    /// </summary>
    /// <param name="dir">位置</param>
    /// <param name="method">文件类型</param>    
    public static DataTable GetDirectoryInfos(string dir, FsoMethod method)
    {
        DataRow row;
        DataTable table = new DataTable();
        table.Columns.Add("name", typeof(string));
        table.Columns.Add("type");
        table.Columns.Add("size", typeof(int));
        table.Columns.Add("content_type");
        table.Columns.Add("createTime", typeof(DateTime));
        table.Columns.Add("lastWriteTime", typeof(DateTime));
        if (method != FsoMethod.File)
        {
            for (int i = 0; i < getDirs(dir).Length; i++)
            {
                row = table.NewRow();
                DirectoryInfo d = new DirectoryInfo(getDirs(dir)[i]);
                long[] numArray = DirInfo(d);
                row[0] = d.Name;
                row[1] = 1;
                row[2] = numArray[0];
                row[3] = "";
                row[4] = d.CreationTime;
                row[5] = d.LastWriteTime;
                table.Rows.Add(row);
            }
        }
        if (method != FsoMethod.Folder)
        {
            for (int j = 0; j < getFiles(dir).Length; j++)
            {
                row = table.NewRow();
                FileInfo info2 = new FileInfo(getFiles(dir)[j]);
                row[0] = info2.Name;
                row[1] = 2;
                row[2] = info2.Length;
                row[3] = info2.Extension.Replace(".", "");
                row[4] = info2.CreationTime;
                row[5] = info2.LastWriteTime;
                table.Rows.Add(row);
            }
        }
        return table;
    }

    /// <summary>
    /// 获取目录列表
    /// </summary>
    private static string[] getDirs(string dir)
    {
        return Directory.GetDirectories(dir);
    }

    /// <summary>
    /// 获取文件列表
    /// </summary>
    private static string[] getFiles(string dir)
    {
        return Directory.GetFiles(dir);
    }

    /// <summary>
    /// 获取文件信息
    /// </summary>
    private static long[] DirInfo(DirectoryInfo d)
    {
        long[] numArray = new long[3];
        long num = 0L;
        long num2 = 0L;
        long num3 = 0L;
        FileInfo[] files = d.GetFiles();
        num3 += files.Length;
        foreach (FileInfo info in files)
        {
            num += info.Length;
        }
        DirectoryInfo[] directories = d.GetDirectories();
        num2 += directories.Length;
        foreach (DirectoryInfo info2 in directories)
        {
            num += DirInfo(info2)[0];
            num2 += DirInfo(info2)[1];
            num3 += DirInfo(info2)[2];
        }
        numArray[0] = num;
        numArray[1] = num2;
        numArray[2] = num3;
        return numArray;
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="path"></param>
    public static void DeleteFile(string path)
    {
        if (File.Exists(path))
        {
            FileInfo fi = new FileInfo(path);
            fi.Delete();
        }
    }

    /// <summary>
    /// 创建文件夹
    /// </summary>
    /// <param name="dir"></param>
    public static void CreateFolder(string dir)
    {
        Directory.CreateDirectory(dir);
    }

    /// <summary>
    /// 删除文件夹
    /// </summary>
    /// <param name="dir">物理路径</param>
    public static void DeleteFolder(string dir)
    {
        string[] dirs = Directory.GetFileSystemEntries(dir);

        foreach (string d in dirs)
        {
            if (File.Exists(d))
            {
                FileInfo fi = new FileInfo(d);
                if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                    fi.Attributes = FileAttributes.Normal;

                File.Delete(d);//直接删除其中的文件
            }
            else
                DeleteFolder(d);//递归删除子文件夹
        }

        Directory.Delete(dir);//删除已空文件夹
    }

    /// <summary>
    /// 获取文件夹大小
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static long FolderSize(string dir)
    {
        long temp = 0;

        //判断当前路径所指向的是否为文件
        if (File.Exists(dir) == false)
        {
            string[] str1 = Directory.GetFileSystemEntries(dir);
            foreach (string s1 in str1)
            {
                temp += FolderSize(s1);
            }
        }
        else
        {
            FileInfo fileInfo = new FileInfo(dir);
            return fileInfo.Length;
        }
        return temp;
    }

    /// <summary>
    /// 文件夹最后修改时间
    /// </summary>
    /// <param name="dir"></param>
    /// <returns></returns>
    public static DateTime FolderLastTime(string dir)
    {
        DateTime time = Directory.GetCreationTime(dir);

        string[] dirs = Directory.GetFileSystemEntries(dir);

        foreach (string d in dirs)
        {
            if (File.Exists(d))
            {
                FileInfo fi = new FileInfo(d);

                DateTime time1 = fi.LastWriteTime;
                if (time1.CompareTo(time) == 1)
                    return time1;
                else
                    return time;
            }
            else
            {
                DateTime time2 = FolderLastTime(d);  //递归
                if (time2.CompareTo(time) == 1)
                    time = time2;
            }
        }

        return time;
    }

    /// <summary>
    /// 读取文件
    /// </summary>
    /// <param name="file">文件名</param>
    /// <returns>文件内容</returns>
    public static string ReadFile(string file)
    {
        string str = "";
        using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read))
        {
            StreamReader reader = new StreamReader(stream, Encoding.Default);
            try
            {
                return reader.ReadToEnd();
            }
            catch
            {
                return str;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }
        }
    }

    /// <summary>
    /// 写入文件
    /// </summary>
    /// <param name="file">文件名</param>
    /// <param name="fileContent">文件内容</param>    
    public static string WriteFile(string file, string fileContent)
    {
        string str;
        FileInfo info = new FileInfo(file);
        if (!Directory.Exists(info.DirectoryName))
        {
            Directory.CreateDirectory(info.DirectoryName);
        }
        FileStream stream = new FileStream(file, FileMode.Create, FileAccess.Write);
        StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
        try
        {
            writer.Write(fileContent);
            str = fileContent;
        }
        catch (Exception exception)
        {
            throw new FileNotFoundException(exception.ToString());
        }
        finally
        {
            writer.Flush();
            stream.Flush();
            writer.Close();
            stream.Close();
        }
        return str;
    }

    public static string GetFriendlySize(long size)
    {
        string ret = null;

        switch ((int)Math.Log((double)size, 1024D))
        {
            case 1:
                ret = (size / 1024F).ToString("#.#") + " KB";
                break;
            case 2:
                ret = (size / 1024F / 1024F).ToString("N1") + " MB";
                break;
            case 3:
                ret = (size / 1024F / 1024F / 1024F).ToString("N1") + " GB";
                break;
            default:
                return (size + " B");
        }
        if (ret.IndexOf(".0") >= 0)
            return ret.Substring(0, ret.Length - 4) + ret.Substring(ret.Length - 2);
        else
            return ret;
    }
}